<style scoped>
  .clientDistribution{
    margin-right: 0.5vw;
    padding: 0 15px;
    background-color: white;
    height: 95vh;
    position: relative;
  }
  .tips{
    position:absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    z-index: 99;
    /* border: 1px solid black; */
    width: 400px;
    height: 300px;
    background: white;
    box-shadow:  0 3px 3px 3px #f4f4f4;
  }
  .tips div:first-child{
    display: flex;
    justify-content: space-between;
    height: 40px;
    width: 100%;
    background: #f4f4f4;
    padding: 10px 15px;
  }
  .tips>div:first-child{
    font-weight: 700;
  }
  .tips div:nth-child(2){
    margin: 15px;
    flex-wrap: wrap;
    height: 77%;
  }
  .tips div:nth-child(2)>p{
    word-wrap: break-word;
    margin-bottom: 15px;
  }
  .tips div:nth-child(3){
    text-align: right;
  }
  .cdb_top{
    display: flex;
    padding: 1.5vh 0;
    border-bottom: 2px solid #f4f4f4;
    white-space:nowrap;
  }
  .cdb_top>p:not(:first-child){
     margin:3px 8px 0 12px;
     /* padding-top: 3px; */
  }
  .jl{
      padding-top: 3px;
      margin: 0 6px 0 0;
    }
  .cdb_button{
    display: flex;
    justify-content: space-between;
    padding: 1.5vh 0;
  }
  .cdb_button>div{
    display:flex;
  }
  .cdb_button>div>div{
    display:flex;
    width: 150px;
    margin-left: 20px;
    border-radius: 20px;
    padding-top: 2px;
    background: #f4f4f4;
  }
  .cdb_button>div>div>i{
    color: #017aff;
    margin: 6px 5px 0 5px;
  }
  .cdb_button>div>div>p:last-child:hover{
    cursor:pointer
  }
  .cdb_button>div>div>p:last-child{
    color: #017aff;
  }
  .tabel1{
    height: 43%;
    width: 100%;
    /* border: 1px solid black; */
    display: flex;
    border-top:15px solid #f4f4f4
  }
  .tabel1>div:first-child{
    width: 49.5%;
    padding: 5px 5px 0 0;
    /* border-left: 10px solid black; */
    margin-right: 0.5%;
  }
  .tabel1>div:last-child{
    width: 49.5%;
    padding-top: 5px;
    /* border: 1px solid black; */
  }
  .border{
    border-right:15px solid #f4f4f4
  }

  .clientDistribution #imgBox{ 
    position: absolute;
    width: auto;
    height: auto;
    z-index: 1;
  }

  .clientDistribution #imgBox .imgTop{
    background-color: #f4f4f4;
    height: 30px;
    padding-left: 10px;
  }
  .clientDistribution #imgBox .imgTop i{
    float: right;
    height: 30px;
    width: 30px;
    line-height: 30px;
  }
  #imgBox .img{
    width: 40vw;
    height: 40vh;
  }
  .clientDistribution #imgBox img{
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
  }
</style>

<style>
  .clientDistribution .el-input__icon{
    line-height: 30px;
  }
  .clientDistribution .cdb_top .sty .el-input__inner{
    width: 3vw;
    height: 30px;
    margin-right: 0.5vw;
    padding: 0 5px;
  }
  .clientDistribution .cdb_top .sty1 .el-input__inner{
    width: 4.5vw;
    height: 30px;
  }
  .clientDistribution .cdb_top .sty2 .el-input__inner{
    width: 8vw;
    height: 30px;
  }
  .clientDistribution .el-date-editor.el-input, .clientDistribution .el-date-editor.el-input__inner{
    width: 8vw;
  }
  .clientDistribution .cdb_top .sty2 .el-input__icon{
    line-height: 32px;
  }
  .clientDistribution .cdb_button .el-checkbox.is-bordered{
    padding: 4px 10px 9px 10px;
    height: 30px;
    margin-right: 2px;
  }
  .clientDistribution .el-select__tags .el-tag{
    max-width: 55%;
  }
</style>

<template>
  <div class="clientDistribution">
    <div class="cdb_top">
      <p class="jl">客户编号</p>
      <div class="sty">
        <el-input v-model="customerNo" @blur="customerNoBlur" :disabled="jxAgent"></el-input>
      </div>
      <div class="sty1">
      <el-select v-model="customerName" @change="e=>{this.customerNo=e}" :disabled="jxAgent">
        <el-option
          v-for="item in customerList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          <span style="float:left">{{item.value}}</span>
          <span style="float:right">{{item.label}}</span>
        </el-option>
        </el-select>
        </div>

        <p>配货序号</p>
        <div class="sty2">
          <el-input v-model="sequence" disabled></el-input>
        </div>

        <p>款号</p>
        <div class="sty2">
          <!-- <el-select v-model="styleNumber" multiple collapse-tags>
            <el-option v-for="item in styleNumberList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select> -->
          <el-input v-model="styleNumber"></el-input>
        </div>

        <p>日期</p>
        <div class="sty2">
          <el-date-picker
            v-model="inputDate"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker>
        </div>

        <p>当季</p>
        <div class="sty2">
          <el-select v-model="quarter" multiple collapse-tags>
          <el-option
            v-for="item in quarterList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
          </el-select>
        </div>

        <p>销售未补</p>
        <div class="sty">
          <el-input placeholder="  <=" disabled></el-input>
        </div>
        <div class="sty1">
          <el-input v-model="sellDay">
            <p slot="suffix" style="line-height:30px">天</p>
          </el-input>
        </div>

        <p>退货</p>
        <div class="sty">
          <el-input placeholder="  <=" disabled></el-input>
        </div>
        <div class="sty1">
          <el-input v-model="outDay">
            <p slot="suffix" style="line-height:30px">天</p>
          </el-input>
        </div>
    </div>

    <div class="cdb_button">
      <div>
        <!-- <el-button type="primary" icon="el-icon-plus">新建</el-button> -->
        <el-button @click="search" icon="el-icon-search" type="primary">查询</el-button>
        <el-button @click="distribution" icon="el-icon-box">配货</el-button>
        <el-button @click="()=>{this.showScreen=true}" icon="el-icon-copy-document">筛选款号</el-button>
        <el-button @click="confirm" icon="el-icon-circle-check" :disabled="isConfirm">确认</el-button>
        <el-button @click="modification" icon="el-icon-edit-outline" :disabled="!isConfirm">反确认</el-button>
        <el-button @click="print" icon="el-icon-printer">列印</el-button>
        <el-button @click="exportData" icon="el-icon-upload2">导出</el-button>
        <el-button @click="dele" icon="el-icon-delete" :disabled="isConfirm">删除</el-button>
        <div>
          <i class="el-icon-question"></i>
          <p>提示：</p>
          <p @click="()=>{this.showTips=true}">操作说明</p>
        </div>
      </div>
      <div>
        <el-checkbox v-model="checked1" label="显示图片" border></el-checkbox>
        <el-checkbox v-model="checked2" label="客订未补" border></el-checkbox>
      </div>
    </div>

    <div class="tabel1">
      <div class="border">
        <el-table
          :data="tableData1"
          height="38vh"
          :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}"
          :cell-style="{padding:0,height:'36px'}"
          style="width: 100%"
          @row-click="rowClick1"
          @selection-change="handleSelectionChange"
          @cell-mouse-enter="cellMouseEnter">
          <el-table-column
            type="selection"
            width="50">
          </el-table-column>
          <el-table-column
            prop="styleNumber"
            label="款号"
            width="160">
          </el-table-column>
          <el-table-column
            prop="colorNo"
            label="色号"
            width="50">
          </el-table-column>
          <el-table-column
            prop="colorName"
            label="颜色"
            width="80">
          </el-table-column>
          <el-table-column
            prop="canMatchRepertory"
            label="可配库存">
          </el-table-column>
          <el-table-column
            prop="repertory"
            label="库存">
          </el-table-column>
          <el-table-column
            prop="customerInput"
            label="客进">
          </el-table-column>
          <el-table-column
            prop="customerSell"
            label="客销">
          </el-table-column>
          <el-table-column
            prop="customerOut"
            label="客退">
          </el-table-column>
          <el-table-column
            prop="customerRepertory"
            label="客存">
          </el-table-column>
          <el-table-column
            prop="sellingPrice"
            label="售价">
          </el-table-column>
        </el-table>
      </div>

      <div>
        <el-table
          :data="tableData2"
          height="38vh"
          :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}"
          :cell-style="{padding:0,height:'36px'}"
          style="width: 100%">
          <el-table-column
            prop="type"
            :label="header"
            width="140">
          </el-table-column>
          <el-table-column
            prop="colorName"
            label="颜色"
            width="80">
          </el-table-column>
          <el-table-column
            prop="c05"
            label="05-XS"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c07"
            label="07-S"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c09"
            label="09-M"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c11"
            label="11-L"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c13"
            label="13-XL"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c15"
            label="15-2L"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c17"
            label="17-3L"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c19"
            label="19-4L"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c21"
            label="21-5L"
            width="70">
          </el-table-column>
          <el-table-column
            prop="c23"
            label="23-6L"
            width="70">
          </el-table-column>
          <el-table-column
            prop="f"
            label="F"
            width="70">
          </el-table-column>
          <el-table-column
            prop="commodityName"
            label="品名"
            width="200">
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="tabel1">
      <div class="border">
        <el-table
          :data="tableData3"
          height="38vh"
          :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}"
          :cell-style="{padding:0,height:'36px'}"
          highlight-current-row
          style="width: 100%"
          ref="table3"
          @row-click="rowClick3">
          <el-table-column
            prop="isPrint"
            label="打印"
            width="50">
          </el-table-column>
          <el-table-column
            prop="allocationCargoSequence"
            label="配货序号"
            width="180">
          </el-table-column>
          <el-table-column
            prop="customerNo"
            label="客户编号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="number"
            label="数量"
            width="80">
          </el-table-column>
          <el-table-column
            prop="allocationCargoTime"
            label="配货日期"
            width="120">
          </el-table-column>
          <el-table-column
            prop="affirm"
            label="确认"
            width="50">
          </el-table-column>
          <el-table-column
            prop="remark"
            label="备注">
            <template slot-scope="scope">

              <el-input size="small" 
                v-model="scope.row['remark']" 
                @keyup.enter.native="remarkEnter($event,{sequence:scope.row['allocationCargoSequence'],result:scope.row['remark']})">
              </el-input>

            </template>
          </el-table-column>
        </el-table>
      </div>

      <div>
        <el-table
          class="tb-edit"
          @cell-click="cellClick"
          @row-click="rowClick4"
          :data="tableData4"
          height="38vh"
          :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}"
          :cell-style="{padding:0,height:'36px'}"
          style="width: 100%">
          <el-table-column
            prop="styleColorNumber"
            label="款色码"
            width="140">
          </el-table-column>
          <el-table-column
            prop="colorName"
            label="颜色"
            width="80">
          </el-table-column>

          <template v-for="i in sizeList" >
            <el-table-column
              :prop="i.prop"
              :label="i.label"
              :key="i.prop"
              width="70">
              <template slot-scope="scope">

                <el-input size="small" 
                  :disabled="isConfirm"
                  v-model="scope.row[i.prop]" 
                  @blur="handleInputBlurResult($event,{index:scope.$index,key:i.prop,result:scope.row[i.prop]})" 
                  @keyup.enter.native="inpEnter">
                </el-input>

              </template>
            </el-table-column>
          </template>
          
          <el-table-column
            prop="number"
            label="小计">
          </el-table-column>
          <el-table-column
            prop="sellingPrice"
            label="售价">
          </el-table-column>
          <el-table-column
            prop="money"
            label="金额">
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="tips" v-if="showTips">
      <div>
        <p>提示</p>
        <i class="el-icon-close" @click="closetip"></i>
      </div>
      <div>
        <p>
          1.选择客户，可以筛选款号，也可以填写多个款号，款号之间以英文逗号分开，可填多少天销售未补或是退货，点
          查询，左上角表格，全选或是复选，点配货静等信息提示。由右下表，填数量，按回车跳单元格。
        </p>
        <p>2.一张单子配完，可在左下角表格备注栏，填写备注，填写按回车，让系统自动保存！</p>
        <div>
        <el-button @click="closetip">取消</el-button>
        <el-button @click="closetip" type="primary">确定</el-button>
        </div>
      </div>
    </div>

    <!-- 筛选款号 -->
    <screen-type
      v-show="showScreen"
      @closeScreenType="()=>{this.showScreen=false}"
      @changeConditions="changeConditions">
    </screen-type>

    <!-- 查看图片 -->
    <div id="imgBox" 
      v-show="showImg"
      ref="imgBoxDom">
      <div class="imgTop">
        <span style="line-height:30px;font-weight:bold;">显示图片</span>
        <i class="el-icon-close" @click="()=>{this.showImg=false}"></i>
      </div>
      <div class="img">
        <img :src="imgSrc" ondragstart='return false;'>
      </div>
    </div>


    <print-area
      v-show=false
      :companyName="companyName"
      :name="printName"
      :inputSequence="sequence"
      :inputDate="printDate"
      :operator="printOperator"
      :printTotal="printTotal"
      :printMoney="printMoney"></print-area>
  </div>
</template>

<script>
const resources = require('../../../config/printCSS')

import { getClient } from '../../../network/client'
import { getQuarter, getNumber } from '../../../network/quarter'
import { getList, getTwoInfoBySequence, affirmYes, affirmNo, del, startAllocation, updateRemark, printConfirm } from '../../../network/customerAllocationTotal'
import { getBarCode } from '../../../network/manufacturer'
import { getSize } from '../../../network/size'
import { getBranded } from '../../../network/branded'
import { getSystemConfig } from '../../../network/operatoryCommand'

import screenType from './childComps/screenType'
import today from '../../../components/mixins/today'

import enterUp from '../../../components/mixins/enterUp'
import outex from '../../../components/mixins/outexp'
import printArea from '../../../components/PrintDistribution'

import table2excel from 'js-table2excel'

export default {
  name: 'client_distribution',
  mixins: [enterUp,today,outex],
  data(){
    return{
      inpList: [],
      showTips: false,
      showScreen: false,
      isConfirm: false,

      pageSession: '',

      imgSrc: '',
      showImg: false,

      customerNo: '',
      customerName: '',
      customerList: [],
      sequence: '',
      styleNumberStr: '',
      styleNumber: '',
      styleNumberList: [],
      inputDate: this.getNowTime(),
      quarter: [],
      quarterList: [],
      sellDay: '',
      outDay: '',
      checked1: false,
      checked2: false,

      originalData: {},

      header: '',
      tableData1: [],
      tableData2: [],
      tableData3: [],
      tableData4: [],
      rightOne: [],
      originalNum: [],

      selected: [],

      sizeList: [
        {
          prop: 'c05',
          label: '05-XS',
          width: ''
        },{
          prop: 'c07',
          label: '07-S',
          width: ''
        },{
          prop: 'c09',
          label: '09-M',
          width: ''
        },{
          prop: 'c11',
          label: '11-L',
          width: ''
        },{
          prop: 'c13',
          label: '13-XL',
          width: ''
        },{
          prop: 'c15',
          label: '15-2L',
          width: ''
        },{
          prop: 'c17',
          label: '17-3L',
          width: ''
        },{
          prop: 'c19',
          label: '19-4L',
          width: ''
        },{
          prop: 'c21',
          label: '21-5L',
          width: ''
        },{
          prop: 'c23',
          label: '23-6L',
          width: ''
        },{
          prop: 'f',
          label: 'F',
          width: ''
        }
      ],

      queryObj: {},
      currentRow: {},

      companyName: '',
      printName: '',
      printDate: '',
      printOperator: '',
      printTotal: '',
      printMoney: '',
      printRemark: '',
      jxQuarter: null,
      jxAgent:null,
      operator:null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter'+'=([^;]+)'))[1],
      // jxAgent: document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))[1] == 1 ? true : false,
      // operator: document.cookie.match(RegExp('jxUser'+'=([^;]+)'))[1]
    }
  },
  watch: {
    $route(a,b){
      if (b.path.indexOf('delete_document') != -1) this.search()
    },
    customerNo(a,b){
      this.customerNo = a.toUpperCase().trim()
    }
  },
  created(){
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let jxAgentVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    this.operator = operatorVal ? operatorVal[1] : null
   if(jxAgentVal){
    this.jxAgent = jxAgentVal[1] == 1 ? true : false
   }
    this.inpList = this.getInput()
    // 随机数赋值
    this.pageSession = Math.ceil(Math.random()*1000000)+''

    // 获取所有客户信息
    this.customerList = []
    getClient({limit:99999}).then(res => {
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach(e => {
          if(e.stop != 1){
            this.customerList.push({value:e.no,label:e.name})
          }
        })
        if (this.jxAgent) {
          for (const i of this.customerList) {
            if (i.label == this.operator) {
              this.customerNo = i.value
              this.customerName = i.value
              break
            }
          }
        }
      }
    })

    // 获取季度
    getQuarter().then(res => {
      if (res.data.code == 200) {
        res.data.data.forEach(e => {
          this.quarterList.push({value:e.name,label:e.name})
        })
      }
    })

    // 获取款号
    // getNumber(['']).then(res => {
    //   if (res.data.code == 200) {
    //     res.data.data.forEach(e => {
    //       this.styleNumberList.push({value:e.styleNumber,label:e.styleNumber})
    //     })
    //   }
    // })

    getSystemConfig().then(res => {
      if (res.data.data) {
        this.companyName = res.data.data.companyName
      }
      
    })
  },
  methods:{
    sibling(e) {
      let s = []
      let pp = e.parentNode.parentNode.children
      for (let j = 0; j < pp.length; j++) {
        let p = pp[j].children
        for(let i = 0, pl = p.length; i < pl; i++) {
          if(p[i] !== e) s.push(p[i])
        }
      }
      return s
    },
    handleInputBlurResult(e,{index,key,result}) {
      // console.log(result)
      // console.log(this.tableData4)
      if (!result || (this.sequence && result == this.originalNum[index][key])) return
      if (this.tableData2[0][key] < result) {
        this.$alert('库存不足', '', {
          confirmButtonText: '确定'
        })
        this.tableData4[index][key] = 0
        return
      }
      
      // let r = /^[1-9][0-9]*$/
      let r = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/
      if (result && result != 0 && result != '0' && result != '') {
        result = result.replace(/\b(0+)/gi,"")
      }
      if (!r.test(result) && result) {
        this.$alert('数量请输入整数', '', {
          confirmButtonText: '确定'
        })
        if (this.sequence && this.originalNum[index][key]) {
          this.tableData4[index][key] = this.originalNum[index][key]
        }
        return
      }

      this.tableData4[index].number = Number(this.tableData4[index].number) + Number(result)
      this.tableData4[index].money = (Number(this.tableData4[index].number) * Number(this.tableData4[index].sellingPrice)).toFixed(2)
      this.$forceUpdate()

      // 客户，日期 变了没
      if (JSON.stringify(this.originalData) != '{}') {
        if (this.originalData.customerNo != this.customerNo || this.originalData.inputDate != this.inputDate) {
          this.sequence = ''
        }
      }

      if (this.sequence == '') {
        this.originalData.customerNo = this.customerNo
        this.originalData.inputDate = this.inputDate
      }
      // 品牌：this.tableData4[index].brandedCompany
      // 款号：this.tableData4[index].styleNumber     
      // 颜色：this.tableData4[index].colorNo
      // 尺码：key
      // 第一个货号：this.tableData4[index].kindsNumber

      let manufacturerBarCode = {}
      let kindsNumber = ''
      let showSize = ''
      // console.log(this.tableData4[index])
      // return
      getBranded({name:this.tableData4[index].brandedName, limit: 9999}).then(a => {
        // console.log(a)
        if (this.tableData4[index].brandedName) {
          return getBarCode({company:a.data.data[0].brandedCompany})
        } else {
          return getBarCode({company:this.tableData4[index].brandedCompany})
        }
      }).then(b => {
        // console.log(b)
        manufacturerBarCode = b.data.data[0]
        return getSize({kind:manufacturerBarCode.sizeKindId,limit: 99999})
      }).then(c => {
        // console.log(c)
        for (const i of c.data.data) {
          if (i.relevanceSize == key) {
            showSize = i.size
            break
          }
        }
        // console.log(showSize)
        if (manufacturerBarCode.styleColorSize) {
          // 型尺色
          if (manufacturerBarCode.styleColor) {
            // 款号与尺码之间有 - 
            if (manufacturerBarCode.colorSize) {
              // 色号与尺码之间有 - 
              kindsNumber = `${this.tableData4[index].styleNumber}-${showSize}-${this.tableData4[index].colorNo}`
            } else {
              // 色号与尺码之间没有 -  
              kindsNumber = `${this.tableData4[index].styleNumber}-${showSize}${this.tableData4[index].colorNo}`
            }
          } else {
            // 款号与尺码之间没有 - 
            if (manufacturerBarCode.colorSize) {
              // 色号与尺码之间有 -  
              kindsNumber = `${this.tableData4[index].styleNumber}${showSize}-${this.tableData4[index].colorNo}`
            } else {
              // 色号与尺码之间没有 - 
              kindsNumber = `${this.tableData4[index].styleNumber}${showSize}${this.tableData4[index].colorNo}`
            }
          }
        } else {
          // 型色尺
          if (manufacturerBarCode.styleColor) {
            // 款号与颜色之间有 - 
            if (manufacturerBarCode.colorSize) {
              // 色号与尺码之间有 -  
              kindsNumber = `${this.tableData4[index].styleNumber}-${this.tableData4[index].colorNo}-${showSize}`
            } else {
              // 色号与尺码之间没有 -  
              kindsNumber = `${this.tableData4[index].styleNumber}-${this.tableData4[index].colorNo}${showSize}`
            }
          } else {
            // 款号与颜色之间没有 - 
            if (manufacturerBarCode.colorSize) {
              // 色号与尺码之间有 -  
              kindsNumber = `${this.tableData4[index].styleNumber}${this.tableData4[index].colorNo}-${showSize}`
            } else {
              // 色号与尺码之间没有 - 
              kindsNumber = `${this.tableData4[index].styleNumber}${this.tableData4[index].colorNo}${showSize}`
            }
          }
        }
        // console.log(kindsNumber)

        // 数量(如果是修改数据，数量 = 新数据 - 旧数据)
        // 是否是修改数据(0:否 1:是)
        // console.log(Boolean(this.sequence))
        let tmp = this.sequence ? this.originalNum[index][key] : 0 
        let number = result
        let isUpdate = 0
        if (this.sequence && this.originalNum[index][key]) {
          number = result - this.originalNum[index][key]
          isUpdate = 1
        }
        {
          this.originalNum[index][key] = this.tableData4[index][key]
        }
        if (!number) return
        let params = {
          pageSession: this.pageSession,
          allocationCargoSequence: this.sequence,
          allocationCargoDate: this.inputDate,
          customerNo: this.customerNo,
          // 是否打开客订未补查询 0：否 1：是
          isOrderNoInput: this.checked2 ? 1 : 0,
          kindsNumber,
          number,
          isUpdate
        }
        return startAllocation(params)
      }).then(res => {
        // console.log(res)
        if (res.data.code == 200) {
          if (this.sequence == '') {
            this.sequence = res.data.data
          }
        }
      })
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
    },
    cellClick(row, column, cell, event){
      // console.log(row)  //当行的全部数据
      // console.log(column)  //当列的全部数据
      // console.log(cell)  //点击格的html代码  td>div
      // console.log(event)  //MouseEvent
      // console.log(cell.innerHTML)
      cell.classList.add('activeCell')
      let s = this.sibling(cell)
      s.forEach(e => {
        e.classList.remove('activeCell')
      })
    },
    inpEnter(e){
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
    },
    remarkEnter(e,{sequence,result}){
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
      updateRemark({
        allocationCargoSequence: sequence,
        remark: result
      }).then(res => {
        if (res.data.code == 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        } else {
          this.$message.error('修改失败')
        }
      })
    },

    closetip(){
      this.showTips = false
    },

    search(){
      this.tableData1 = []
      this.tableData2 = []
      this.tableData3 = []
      this.tableData4 = []
      this.sequence = ''
      this.isConfirm = false

      if (!this.customerNo) {
        this.$message.info("客户不能为空")
        return
      }

      // let sn = ''
      // if (this.styleNumber.length) {
      //   for (const e of this.styleNumber) {
      //     if (sn == '') {
      //       sn = `'${e}'`
      //     } else {
      //       sn = `${sn},'${e}'`
      //     }
      //   }
      // }

      if (this.styleNumber && !this.styleNumberStr) {
        let tmp = this.styleNumber.split(',')
        tmp.forEach(e => {
          if (!this.styleNumberStr) {
            this.styleNumberStr = "'" + e + "'"
          } else {
            this.styleNumberStr += (",'" + e + "'")
          }
        })
      }

      let q = ''
      if (this.quarter.length) {
        for (const e of this.quarter) {
          if (q == '') {
            q = `'${e}'`
          } else {
            q = `${q},'${e}'`
          }
        }
      }
      let params = {
        pageSession: this.pageSession,
        allocationCargoDate: this.inputDate,
        customerNo: this.customerNo,
        styleNumber: this.styleNumberStr,
        quarter: q,
        sellDay: this.sellDay,
        outDay: this.outDay,
        // 是否打开客订未补查询 0：否 1：是
        isOrderNoInput: this.checked2 ? 1 : 0,
      }
      // console.log(params)
      getList(params).then(res => {
        if (res.data.code == 200 && res.data.data) {
          res.data.data.leftTwo.forEach(e => {
            e.allocationCargoTime = e.allocationCargoTime.slice(0,10)
            e.isPrint = e.havePrint ? '已' : '未'
          })

          this.tableData1 = res.data.data.leftOne
          this.tableData3 = res.data.data.leftTwo
          this.rightOne = res.data.data.rightOne
        } else {
          this.$message.info('暂无数据')
        }
      })
    },
    // 配货
    distribution(){
      this.sequence = ''
      this.isConfirm = false
      this.originalNum = []
      this.tableData2 = []
      this.$refs.table3.setCurrentRow({})
      this.selected.forEach(f => {
        f.number = 0
        f.money = 0
        this.originalNum.push({})
      })
      
      this.tableData4 = this.selected
      this.inpList = this.getInput()
      // console.log(this.tableData4)
    },
    // 确认
    confirm(){
      if (!this.sequence) {
        this.$message.warning('请选择一条数据再进行确认操作')
        return
      }
      affirmYes({sequence: this.sequence}).then(res => {
        if (res.data.code == 200) {
          this.search()
          this.$message({
            message: '确认成功',
            type: 'success'
          })
        } else {
          this.$message.error('确认失败')
        }
      })
    },
    // 反确认
    modification(){
      if (!this.sequence) {
        this.$message.warning('请选择一条数据再进行反确认操作')
        return
      }
      affirmNo({sequence: this.sequence}).then(res => {
        if (res.data.code == 200) {
          this.sequence = ''
          this.search()
          this.$message({
            message: '反确认成功',
            type: 'success'
          })
        } else {
          this.$message.error('反确认失败')
        }
      })
    },
    // 列印
    print(){
      if (!this.sequence) {
        this.$message.warning('请先选择一条数据')
        return
      }
      for (const i of this.customerList) {
        if (this.customerNo == i.value) {
          this.printName = this.customerNo + '_' + i.label
          break
        }
      }
      this.printTotal = 0
      this.printMoney = 0
      this.clearPrintTable()
      this.$confirm('是否使用A4纸打印', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        this.openPrint(true)
      }).catch(action => {
        if (action == 'cancel') {
          this.openPrint(false)
        }
      })
      // console.log(this.printName)
    },
    openPrint(isA4, x=1, id='printTable'){
      let index = --x
      let printTable = document.getElementById(id)
      let length = this.tableData4.length
      
      for (index; index < length; index++) {
        const e = this.tableData4[index]
        this.printTotal += Number(e.number)
        this.printMoney += Number(e.money)

        let row = printTable.insertRow(printTable.FetchRowCount)
        row.insertCell(0).innerHTML = index+1
        row.insertCell(1).innerHTML = e.styleNumber + '-' + e.colorNo
        row.insertCell(2).innerHTML = e.colorName
        row.insertCell(3).innerHTML = e.commodityName
        row.insertCell(4).innerHTML = e.c05 || ''
        row.insertCell(5).innerHTML = e.c07 || ''
        row.insertCell(6).innerHTML = e.c09 || ''
        row.insertCell(7).innerHTML = e.c11 || ''
        row.insertCell(8).innerHTML = e.c13 || ''
        row.insertCell(9).innerHTML = e.c15 || ''
        row.insertCell(10).innerHTML = e.c17 || ''
        row.insertCell(11).innerHTML = e.c19 || ''
        row.insertCell(12).innerHTML = e.c21 || ''
        row.insertCell(13).innerHTML = e.c23 || ''
        row.insertCell(14).innerHTML = e.f || ''
        row.insertCell(15).innerHTML = e.number
        row.insertCell(16).innerHTML = e.sellingPrice
        row.insertCell(17).innerHTML = e.money

        if (isA4) {
          if (parseInt((index+1)/33) && (index+1)%33 == 0 && (index+1) != length) {
            // console.log('33倍数')
            let pageIndex = index + 3 - (parseInt(index/33)*33)
            // console.log(pageIndex)
            // console.log(index+1)    // 33
            // console.log(length)     // 36
            // let startingPoint = index - 32
            // let pageTotal = 0
            // let pageMoney = 0
            // for (let j = startingPoint; j <= index; j++) {
            //   pageTotal += this.tableData4[j].number
            //   pageMoney += this.tableData4[j].sellingPriceMoney
            // }

            // let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            // rowEnd.insertCell(0).innerHTML = '本页小计：'
            // printTable.rows[pageIndex].cells[0].colSpan = '2'
            // rowEnd.insertCell(1).innerHTML = pageTotal
            // printTable.rows[pageIndex].cells[1].colSpan = '2'
            // rowEnd.insertCell(2).innerHTML = '汇总金额：'
            // printTable.rows[pageIndex].cells[2].colSpan = '4'
            // rowEnd.insertCell(3).innerHTML = pageMoney
            // printTable.rows[pageIndex].cells[3].colSpan = '10'

            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '备注：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = this.printRemark
            printTable.rows[pageIndex].cells[1].colSpan = '16'

            let newHead = document.createElement('div')
            newHead.classList.add("addPrintHead")
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${(index+1)/33 * 29.7 + 3}cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.companyName}${this.jxQuarter}客户配货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户：${this.printName}</p>
                <p style="margin: 5px 0;">配货序号：${this.sequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">配货日期：${this.printDate}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index+1)/33}`
            // console.log(tableId)
            let tableDom = document.createElement("table")
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <tr>
                <td style="width: 4%;padding: 0;text-align: center;" rowspan="2">序号</td>
                <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">型色</td>
                <td style="width: 8%;padding: 0;text-align: center;" rowspan="2">颜色</td>
                <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">品名</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">05</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">07</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">09</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">11</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">13</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">15</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">17</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">19</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">21</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">23</td>
                <td style="width: 3.8%;padding: 0;text-align: center;">F</td>
                <td rowspan="2" style="text-align: center;width: 5%;">数量</td>
                <td rowspan="2" style="text-align: center;width: 5%;">售价</td>
                <td rowspan="2" style="text-align: center;">金额</td>
              </tr>
              <tr>
                <td style="text-align: center;border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                <td style="text-align: center;border-top: 1px dotted;">S</td>
                <td style="text-align: center;border-top: 1px dotted;">M</td>
                <td style="text-align: center;border-top: 1px dotted;">L</td>
                <td style="text-align: center;border-top: 1px dotted;">XL</td>
                <td style="text-align: center;border-top: 1px dotted;">2L</td>
                <td style="text-align: center;border-top: 1px dotted;">3L</td>
                <td style="text-align: center;border-top: 1px dotted;">4L</td>
                <td style="text-align: center;border-top: 1px dotted;">5L</td>
                <td style="text-align: center;border-top: 1px dotted;">6L</td>
                <td style="text-align: center;border-top: 1px dotted;"></td>
              </tr>
            `
            // console.log(tableDom)
            // console.log(index)
            this.insertAfter(tableDom, newHead)
            this.openPrint(true,index+2,tableId)
            return
          }
          if ((index+1) == length) {
            let pageIndex = index + 3 - (parseInt(index/33)*33)
            // console.log('最后一行')
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '备注：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = this.printRemark
            printTable.rows[pageIndex].cells[1].colSpan = '16'
          }
        } else {
          // A4一半
          if (parseInt((index+1)/12) && (index+1)%12 == 0 && (index+1) != length) {
            // console.log('12倍数')
            let pageIndex = index + 3 - (parseInt(index/12)*12)
            // console.log(pageIndex)
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '备注：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = this.printRemark
            printTable.rows[pageIndex].cells[1].colSpan = '16'

            let newHead = document.createElement('div')
            newHead.classList.add("addPrintHead")
            newHead.innerHTML = `
              <p class="rightTag" style="top: ${(index+1)/12 * 14.85 + 3}cm;">白联仓库 红联财务 黄联客户</p>
              <span class="printHead">
                ${this.companyName}${this.jxQuarter}客户配货单
              </span>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">客户：${this.printName}</p>
                <p style="margin: 5px 0;">配货序号：${this.sequence}</p>
              </div>
              <div class="info" style="height: 25px;">
                <p style="margin: 5px 0;">配货日期：${this.printDate}</p>
              </div>
            `
            newHead.style.pageBreakBefore = 'always'
            this.insertAfter(newHead, printTable)

            let tableId = `printTable${(index+1)/12}`
            // console.log(tableId)
            let tableDom = document.createElement("table")
            tableDom.border = '1'
            tableDom.align = 'center'
            tableDom.id = tableId
            tableDom.innerHTML = `
              <tr>
                <td style="width: 4%;padding: 0;text-align: center;" rowspan="2">序号</td>
                <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">型色</td>
                <td style="width: 8%;padding: 0;text-align: center;" rowspan="2">颜色</td>
                <td style="width: 15%;padding: 0;text-align: center;" rowspan="2">品名</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">05</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">07</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">09</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">11</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">13</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">15</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">17</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">19</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">21</td>
                <td style="width: 3.8%;padding: 0;text-align: center;" nowrap="nowrap">23</td>
                <td style="width: 3.8%;padding: 0;text-align: center;">F</td>
                <td rowspan="2" style="text-align: center;width: 5%;">数量</td>
                <td rowspan="2" style="text-align: center;width: 5%;">售价</td>
                <td rowspan="2" style="text-align: center;">金额</td>
              </tr>
              <tr>
                <td style="text-align: center;border-top: 1px dotted;border-left: 1px dotted;">XS</td>
                <td style="text-align: center;border-top: 1px dotted;">S</td>
                <td style="text-align: center;border-top: 1px dotted;">M</td>
                <td style="text-align: center;border-top: 1px dotted;">L</td>
                <td style="text-align: center;border-top: 1px dotted;">XL</td>
                <td style="text-align: center;border-top: 1px dotted;">2L</td>
                <td style="text-align: center;border-top: 1px dotted;">3L</td>
                <td style="text-align: center;border-top: 1px dotted;">4L</td>
                <td style="text-align: center;border-top: 1px dotted;">5L</td>
                <td style="text-align: center;border-top: 1px dotted;">6L</td>
                <td style="text-align: center;border-top: 1px dotted;"></td>
              </tr>
            `
            // console.log(tableDom)
            // console.log(index)
            this.insertAfter(tableDom, newHead)
            this.openPrint(false,index+2,tableId)
            return
          }
          if ((index+1) == length) {
            let pageIndex = index + 3 - (parseInt(index/12)*12)
            // console.log('最后一行')
            let rowEnd = printTable.insertRow(printTable.FetchRowCount)
            rowEnd.insertCell(0).innerHTML = '备注：'
            printTable.rows[pageIndex].cells[0].colSpan = '2'
            rowEnd.insertCell(1).innerHTML = this.printRemark
            printTable.rows[pageIndex].cells[1].colSpan = '16'
          }
        }
      }

      // console.log(this.styleList)
      let int = setInterval(() => {
        // if (this.printStyle) {
          clearInterval(int)

          printConfirm({sequence:this.sequence}).then(res => {
            // console.log(res)
            if (res.status == 200) {
              this.search()
            }
          })

          let printHtml = document.getElementById('p').innerHTML
          let wind = window.open("",'newwindow', 'height=500, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
          wind.document.body.innerHTML = printHtml
          let style = document.createElement('style')
          style.type = 'text/css'
          style.innerHTML = resources.printCSS
          wind.document.head.appendChild(style)
          wind.print()
          return false
        // }
      }, 500)
    },
    clearPrintTable(){
      let printTable = document.getElementById("printTable")
      let trs = printTable.getElementsByTagName("tr")
      let len = trs.length - 1
      for(let i = len; i > 1; i--) {
        printTable.deleteRow(i)
      }

      let printArea = document.getElementById("p")
      let tables = printArea.getElementsByTagName('table')
      len = tables.length
      for (let i = 1; i < len; i++) {
        tables[1].remove()
      }
      let addPrintHeads = document.getElementsByClassName('addPrintHead')
      len = addPrintHeads.length
      for (let i = 0; i < len; i++) {
        addPrintHeads[0].remove()
      }
    },
    // insertAfter(p,header1) // 因为js没有直接追加到指定元素后面的方法 所以要自己创建一个方法
    insertAfter( newElement, targetElement ){ // newElement是要追加的元素 targetElement 是指定元素的位置
      let parent = targetElement.parentNode // 找到指定元素的父节点
      if( parent.lastChild == targetElement ){ // 判断指定元素的是否是节点中的最后一个位置 如果是的话就直接使用appendChild方法
        parent.appendChild( newElement, targetElement )
      }else{
        parent.insertBefore( newElement, targetElement.nextSibling )
      }
    },


    // 删除
    dele(){
      if (!this.sequence) return
      this.$router.push({path: '/delete_document', query: this.queryObj})
      this.$store.commit('addNav',{label:'客户配货删单',name:'delete_document'})
    },
    rowClick1(row){
      if (!this.checked1) return
      console.log(row)
      let imgBox=document.getElementById("imgBox")
      if (!this.showImg) {
        imgBox.style.left = "400px"
        imgBox.style.top = "150px"
        this.showImg = true
      }
      this.imgSrc = row.image || (this.showImg = false)
    },

    rowClick3(row){
      // console.log(row)
      this.sequence = row.allocationCargoSequence
      this.printDate = row.allocationCargoTime
      this.printOperator = row.operator
      this.printRemark = row.remark
      this.queryObj = {
        type: 6,
        sequence: row.allocationCargoSequence,
        no: row.customerNo,
        affirm: row.affirm,
        allocationCargoTime: row.allocationCargoTime,
        remark: row.remark,
        // isOrderNoInput: this.checked2 ? 1 : 0
      }
      this.currentRow = row
      if (row.affirm) {
        this.isConfirm = true
      } else {
        this.isConfirm = false
      }
      getTwoInfoBySequence({
        customerNo: row.customerNo,
        sequence: row.allocationCargoSequence
      }).then(res => {
        if (res.data.code == 200) {
          this.tableData4 = res.data.data
          this.originalNum = []
          this.tableData4.forEach((e,i) => {
            this.originalNum.push({})
            this.sizeList.forEach(f => {
              this.originalNum[i][f.prop] = e[f.prop]
            })
          })
        }
      })
    },
    rowClick4(row){
      // console.log(row)
      this.header = row.styleColorNumber
      for (const key in this.rightOne) {
        if (this.rightOne.hasOwnProperty(key)) {
          const element = this.rightOne[key]
          if (key == row.styleColorNumber) {
            this.tableData2 = element
            return
          }
        }
      }
    },

    cellMouseEnter(row, column, cell, event){
      // console.log(column)
      // console.log(cell)
      // console.log(event)
    },
    checkImg(row){
      let imgBox=document.getElementById("imgBox")
      imgBox.style.left = "400px"
      imgBox.style.top = "150px"
      
      // console.log(row)
      for (const i of this.kindsNumberList) {
        if (i.styleNumber == row.styleNumber && i.colorName == row.colorName) {
          // this.imgSrc = i.image
          this.showImg = true
          break
        }
      }
    },

    // 客户编号失去焦点
    customerNoBlur(){
      if (this.customerNo != '') {
        for (const i of this.customerList) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            return
          }
        }
        this.$message.warning('无此客户编号')
        this.customerNo = ''
        this.customerName = ''
      } else {
        this.customerName = ''
      }
    },
    handleSelectionChange(e){
      this.selected = e
    },
    changeConditions(d){
      // console.log(d)
      this.quarter = []
      this.styleNumber = ''
      this.styleNumberStr = ''
      
      if (d.length) {
        d.forEach(e => {
          this.quarter.push(e.quarter)
          if (!this.styleNumberStr) {
            this.styleNumber = e.styleNumber
            this.styleNumberStr = "'" + e.styleNumber + "'"
          } else {
            this.styleNumber += (',' + e.styleNumber)
            this.styleNumberStr += (",'" + e.styleNumber + "'")
          }
        })
      }
    },

    exportData(){
      // this.tableData3.forEach(e => {
      //   e.customerNo += '&nbsp;'
      // });
      let column = [
        {key: "isPrint",title: "打印",type: 'text'},
        {key: "allocationCargoSequence",title: "配货序号",type: 'text'},
        {key: "customerNo",title: "客户编号",type: 'text'},
        {key: "number",title: "数量",type: 'text'},
        {key: "allocationCargoTime",title: "配货日期",type: 'text'},
        {key: "affirm",title: "确认",type: 'text'},
        {key: "remark",title: "备注",type: 'text'}
      ]
      table2excel(column, this.tableData3, "客户配货表.xls")
    }
  },
  components:{
    screenType,
    printArea
  },
  mounted(){
    imgBox.onmousedown = function(event){
      let imgBox=document.getElementById("imgBox")
      let rex=event.clientX - imgBox.offsetLeft
      let rey=event.clientY - imgBox.offsetTop
      document.onmousemove = e=>{ 
        let xX = 0
        let yY = 0
        xX=e.clientX
        yY=e.clientY
        imgBox.style.left = (xX-rex) + "px"
        imgBox.style.top = (yY-rey) + "px"
      }
    }
    document.onmouseup=()=>{
      document.onmousemove = null
    }
  }
}
</script>